<template>
  <div class="drag-container"  @mousedown="startDrag" @mouseup="endDrag"
    @mousemove.prevent="onMouseMove" @mouseleave="endDrag">
    <div v-for="(item, index) in checkboxList" :key="index" class="checkbox-item">
      <input type="checkbox" :value="item.value" v-model="selectedItems" />
      <span @click="toggleCheckbox(item.value)">{{ item.label }}</span>
    </div>

    <div v-show="dragging" class="drag-preview" :style="dragPreviewStyle"></div>

    <!-- <Teleport to="body">
      <div v-show="dragging" class="drag-preview" :style="dragPreviewStyle"></div>
    </Teleport> -->

    <!-- 将内容传送到id为aaa的元素下 ,但是该元素得先存在-->
    <!-- <Teleport to="#drag-container"> 
      <div v-show="dragging" class="drag-preview" :style="dragPreviewStyle"></div>
    </Teleport> -->

  </div>
</template>

<script setup>
import { ref } from 'vue';

const checkboxList = ref([
  { label: '选项1', value: 'option1' },
  { label: '选项2', value: 'option2' },
  { label: '选项3', value: 'option3' },
  { label: '选项4', value: 'option4' },
  { label: '选项5', value: 'option5' },
]);

const selectedItems = ref([]);
let startX;
let startY;
let endX;
let endY;
let 拖拽距离够大 = false;
let dragging = false;
const dragPreviewStyle = ref({});
const 拖拽阈值 = 5; // 单位：像素  

const startDrag = (e) => {
  startX = e.clientX;
  startY = e.clientY;
  拖拽距离够大 = false;
  dragging = true;
  dragPreviewStyle.value = {}; // 清除之前的拖拽预览样式  
};

const endDrag = (e) => {
  dragging = false;
  if (!拖拽距离够大) {
    toggleCheckbox(e); // 处理点击事件  
  } else {
    handleDragEnd(e);
  }
  拖拽距离够大 = false; // 重置拖拽状态  
  dragPreviewStyle.value = {}; // 清除拖拽预览样式  
};

const onMouseMove = (e) => {
  if (dragging) {
    endX = e.clientX;
    endY = e.clientY;
    const distanceX = endX - startX;
    const distanceY = endY - startY;

    // 如果移动距离超过阈值，认为是拖拽  
    if (!拖拽距离够大 && (Math.abs(distanceX) > 拖拽阈值 || Math.abs(distanceY) > 拖拽阈值)) {
      拖拽距离够大 = true; // 设置为拖拽状态  
    }

    if (拖拽距离够大) {
      // const containerRect = e.currentTarget.getBoundingClientRect();
      const element0 = e.currentTarget;

      // 页面有多个的话，id会重复
      // const element0 = document.getElementById('drag-container');
      const containerRect = element0.getBoundingClientRect();
      // console.log('e: ', e);
      // console.log(`e.currentTarget 👉`,e.currentTarget)
      console.log(`containerRect 👉`,containerRect)
      dragPreviewStyle.value = {
        left: Math.min(startX, endX) - containerRect.left + 'px',
        top: Math.min(startY, endY) - containerRect.top + 'px',
        width: Math.abs(endX - startX) + 'px',
        height: Math.abs(endY - startY) + 'px',
        position: 'absolute',
        backgroundColor: 'rgba(200, 200, 255, 0.5)',
        border: '1px dashed #aaa',
        pointerEvents: 'none',
      };
    }
  }
};

const handleDragEnd = (e) => {
  const elements = document.querySelectorAll('.drag-container input[type="checkbox"], .drag-container span');
  const rect = {
    left: Math.min(startX, endX),
    top: Math.min(startY, endY),
    right: Math.max(startX, endX),
    bottom: Math.max(startY, endY),
  };

  const isCtrlPressed = e.ctrlKey;
  let arr = []
  for (const element of elements) {
    const elementRect = element.getBoundingClientRect();
    const isInRangeX = !(rect.right < elementRect.left || rect.left > elementRect.right);
    const isInRangeY = !(rect.bottom < elementRect.top || rect.top > elementRect.bottom);
    if (isInRangeX && isInRangeY) {
      console.log(`element.tagName 👉`, element.tagName)
      let 目标元素 = element
      if (element.tagName === 'SPAN') {
        目标元素 = element.previousElementSibling; // 获取对应的复选框  
        // console.log(`目标元素 👉`,目标元素)
      }
      arr.push(目标元素)
    }
  }
  // 去重复
  arr = [...new Set(arr)];
  for (const iterator of arr) {
    if (isCtrlPressed) {
      // 如果CTRL键被按下，选中所有复选框  
      iterator.checked = true;
      addToSelectedItems(iterator.value);
    } else {
      toggleCheckboxSelection(iterator); // 切换选中状态  
    }
  }

};

const toggleCheckboxSelection = (checkbox) => {
  checkbox.checked = !checkbox.checked; // 切换复选框状态  
  const value = checkbox.value;
  if (checkbox.checked) {
    addToSelectedItems(value);
  } else {
    removeFromSelectedItems(value);
  }
};

const addToSelectedItems = (value) => {
  if (!selectedItems.value.includes(value)) {
    selectedItems.value.push(value);
  }
};

const removeFromSelectedItems = (value) => {
  const index = selectedItems.value.indexOf(value);
  if (index > -1) {
    selectedItems.value.splice(index, 1);
  }
};

const toggleCheckbox = (value) => {
  const checkbox = checkboxList.value.find(item => item.value === value);
  if (checkbox) {
    const input = document.querySelector(`input[value="${value}"]`);
    toggleCheckboxSelection(input);
  }
};

</script>

<style scoped>
.drag-container {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;
  user-select: none;
  position: relative;
  /* 以便定位预览框 */
}

.drag-container .checkbox-item {
  display: flex;
  align-items: center;
}

.drag-preview {
  background-color: rgba(200, 200, 255, 0.5);
  border: 1px dashed #aaa;
  user-select: none;
  position: absolute;
  z-index: 10;
  /* 确保拖拽预览在最上层 */
}
</style>